﻿using PageAdmin.Utils.ORM;
using System;
using System.Reflection;

namespace PageAdmin.Utils.BLL
{
    /// <summary>
    /// 获取实体内容页数据
    /// </summary><T>:IAdd<T> where T : class, new()
    public class GetDetailDataBLL<T> : IGetDetailData<T> where T : class, new()
    {

        /// <summary>
        /// 执行后的委托
        /// </summary>
        public Action<T> Executed { get; set; }

        /// <summary>
        /// 数据库对象
        /// </summary>
        private DataBaseContext _DbContext;


        public GetDetailDataBLL(DataBaseContext dataBaseContext)
        {
            _DbContext = dataBaseContext;
        }

        /// <summary>
        /// 根据id获取实体。
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetData(int id)
        {
            DbSet<T> dbSet=_DbContext.DbSet<T>();
            T tModel = dbSet.Find(id);
            if (tModel != null)
            {
                SetDetailData(dbSet, tModel, id);
                Executed?.Invoke(tModel);//执行后的委托
            }
            return tModel;
        }

        /// <summary>
        /// 根据条件，排序和参数获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetData(string condition, string orderBy,object dbParameters = null)
        {
            DbSet<T> dbSet = _DbContext.DbSet<T>();
            T tModel = dbSet.QueryFirst(condition, orderBy, dbParameters);
            if (tModel != null)
            {
                var proInfo = dbSet.ModelType.GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (proInfo != null)
                {
                    int detailId = (int)proInfo.GetValue(tModel, null);
                    SetDetailData(dbSet, tModel, detailId);
                    Executed?.Invoke(tModel);//执行后的委托
                }
            }
            return tModel;
        }



        /// <summary>
        /// 设置相关数据,附件数据，中间表数据，关联表数据
        /// </summary>
        private void SetDetailData(DbSet<T> dbSet,T model,int detailId)
        {
            AttachmentDataBLL.SetAttachmentListProperty(dbSet, model, detailId); //设置附件
            SubdataBLL.SetSubdata(_DbContext, model, detailId, true); //设置子数据
            RelateDataBLL.SetRelateData(_DbContext, model, true);//设置管理数据
        }

    }
}